package main

import (
	"context"
	"flag"
	"fmt"
	"gitee.com/enzolwb/my-web-scaffold/models"
	"gitee.com/enzolwb/my-web-scaffold/pkg/app/validation"
	mylog "gitee.com/enzolwb/my-web-scaffold/pkg/cuslog"
	"gitee.com/enzolwb/my-web-scaffold/pkg/gredis"
	"gitee.com/enzolwb/my-web-scaffold/pkg/setting"
	"gitee.com/enzolwb/my-web-scaffold/routers"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

var confPath = flag.String("conf", "./conf/dev/app.ini", "请输入配置文件地址")

func main() {
	//解析命令行参数
	flag.Parse()
	if *confPath == "" {
		flag.Usage()
		os.Exit(1)
	}

	//加载配置项
	InitModules(*confPath)

	//初始化路由
	router := demo.InitRouter()

	s := &http.Server{
		Addr:           fmt.Sprintf(":%d", setting.ServerSetting.HttpPort),
		Handler:        router,
		ReadTimeout:    setting.ServerSetting.ReadTimeout,
		WriteTimeout:   setting.ServerSetting.WriteTimeout,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := s.ListenAndServe(); err != nil {
			log.Printf("Listen: %s\n", err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit

	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}

	log.Println("Server exiting")
}

//InitModules 加载配置项 不使用init方式在于可以控制、先后顺序 以及选择性加载等
func InitModules(confPath string) {
	//配置项的映射
	setting.Setup(confPath)
	//日志 启动自定义配置的
	mylog.SetUp()
	//DB连接池和权限启动
	models.Setup(confPath)

	//请求验证器 启动
	if err := validation.SetUp(); err != nil {
		log.Fatal(err)
	}
	//redis 连接池启动
	if err := gredis.Setup(); err != nil {
		log.Fatal(err)
	}
}
